package org.springblade.feign;

import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import org.springblade.common.constant.ProtocolConstant;
import org.springblade.entity.ProtocolAnalysis;
import org.springblade.handle.MsgDispatcher;
import org.springblade.protocol.tcp.client.SocketClient;
import org.springblade.protocol.tcp.server.SocketServer;
import org.springframework.web.bind.annotation.RestController;


/**
 * DeviceConnectClient
 * @author lijiamin
 */
@RestController
@AllArgsConstructor
public class DeviceConnectClient implements IDeviceConnectClient {

	/**
	 * 重新连接
	 * @param ipAddr
	 * @param port
	 * @param protocol
	 */
	@Override
	public void reconnection(String ipAddr, Integer port, Integer protocol) {
		switch (protocol) {
			case ProtocolConstant.TCP_SERVER:
				SocketClient.connectServer(ipAddr, port);
				break;
			case ProtocolConstant.TCP_CLIENT:
				SocketServer.closeConnect(ipAddr, port);
				break;
		}
	}

	/**
	 * 指令发送
	 * @param ipAddr
	 * @param port
	 * @param protocol
	 * @param protocolAnalysisS
	 */
	@Override
	public void sendCode(String ipAddr, Integer port, Integer protocol, String protocolAnalysisS) {
		ProtocolAnalysis protocolAnalysis = JSONObject.parseObject(protocolAnalysisS, ProtocolAnalysis.class);
		MsgDispatcher.getCodecAdapter(protocol).encode(ipAddr, String.valueOf(port), protocolAnalysis.getMatchingValue(), protocolAnalysis.getId());
	}
}
